/**
 * Created by Administrator on 2018/4/9.
 */




var USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1";

/**
 * wap版本的卡列表序号，默认为0
 */
var wapCreditCardNum = 0;

load("js/luaclient.js")



var v4_boc_mobile_credit_java_funcs={
    checkProxyAvailable: function () {
        var flag= checkProxyAvailableOnWap()
        return flag
    },
    checkTargetWebsiteAvailable: function(){
        return true;

    },
    checkControlAvailable: function () {
        return true;
    },
    login:function () {
        inputImgOnWap();
    },
    crawl: function () {
        crawlCreditOnWap()
    },
    exitLogin: function () {
    }
}
/**
 * ------------业务方法开始-------------
 */


function checkProxyAvailableOnWap() {

    var checkProxyFunc = function () {
        var url='https://mbs.boc.cn/BOCWapBank/WEBSPortalMenuNew.do?_locale=zh_CN';
        var loginHtml=executeGet(url, null);
        storeDataToFile(context, loginHtml, "wap_loginHtml.html");
        var flag = loginHtml.contains("代理服务器没有响应") || loginHtml.contains("无法显示此页")
        return !flag
    }
    var getProxyInfo = function () {
        return "代理ip异常"
    }
    return assertTrueOrThrowException("", checkProxyFunc, getProxyInfo)
}
/**
 *  目前不需要，在inputImg处和图片一起提交
 * @returns {*}
 */
function inputImgOnWap() {
    // 登录
    var taskKey = context.get(Constants.LUA_TASK_KEY);
    var url = "https://mbs.boc.cn/BOCWapBank/ImageValidation/validation542261878.gif";

    var toByteArray = RequestUtil.getAsBytes(url);
    context.put(TASK_IMG_BYTES, toByteArray);
    // var captchaStr = waitImgCodeBySeconds(context, 180, true);
    context.put(TASK_IMG_REGEX,"[0-9a-zA-Z]{4}");
    var captchaStr = waitImgCodeBySecondsByJs(context,120,true,3);
    // logger.info("当前验证码路径为{}，验证码结果为{}", path, captchaStr);
    logger.info("中国 taskKey={} wap版本登录！", taskKey);
    var loginUrl = "https://mbs.boc.cn/BOCWapBank/LOGNWelcomeResult.do";
    //TODO 这里可能会需要添加header等信息 、或者cookie等信息
    var param = new HashMap();
    //TODO 这里需要对密码或者用户名进行进一步的校验
    var password = context.get(Constants.LUA_TASK_TOKEN);
    var loginNoTemp = getLoginParams(context)[0];
    param.put("LoginName", loginNoTemp);
    param.put("Password", password);
    param.put("ValidationChar", captchaStr);
    param.put("Submit", "登录手机银行");
    var loginAfterHtml = executePostWithParam(loginUrl, param, null);
    storeDataToFile(context, loginAfterHtml, "wap_loginAfter.html");
    //这里去检测中国登录成功后的页面
    logger.info("中国 taskKey={}验证登录是否成功", taskKey);

    // 在这里
    var loginResult = {}
    loginResult.loginAfterHtml = loginAfterHtml;
    var checkLogin = function (loginResult) {
        var doc = Jsoup.parse(loginResult.loginAfterHtml);
        var elements = doc.select(".wapbody");
        if (!elements.isEmpty()) {
            var loginAfterInfo = elements.html().trim().replaceAll("\r", "").replaceAll("\n", "");
            logger.info("中国 taskKet={},取得登录后的提示信息：{}", taskKey, loginAfterInfo);
            if (elements.html().trim().contains("欢迎使用中国银行手机银行，您的电子银行客户号为")) {
                logger.info("中国银行 taskKey={}登录成功！", taskKey);
                var info = elements.html();
                name_on_card_wap = info.substring(info.indexOf("尊敬的") + 3, info.indexOf("先生"));
                return true;
            }
            // 这里为其他的异常情况，可能有 验证码错误、用户名错误、密码错误、 默认返回false 如果找到的错误信息为空说明 一个新的错误信息
          if (loginAfterInfo.contains("验证码超时，请刷新后重新输入"))
            {//这里可能有其他异常  验证码超时的异常
                logger.info("中国taskKey={},验证码超时，重新输入验证码");
                loginResult.errorMsg = "图片验证码超时";
                return false;
            } else {
              loginResult.errorMsg = loginAfterInfo;
            }
        } else {
            //TODO 如果找到的错误信息为空说明 一个新的错误信息，也可能为登录成功没有找到，那么先默认为登录成功 增加成功率
            logger.info("中国 taskKey={}当前获取错误信息元素为空，默认登录成功", taskKey);
            return true;
        }
    }
    var getLoginErroMsg = function (loginResult) {
        return loginResult.errorMsg;
    }
    return assertTrueOrThrowException(loginResult, checkLogin, getLoginErroMsg)
}
function crawlCreditOnWap() {
    var taskKey = context.get(Constants.LUA_TASK_KEY);
    var dataList = new ArrayList();
    context.put("credit_data", dataList);
    logger.info("中国 taskKey={},wap版本，开始抓取信用卡！", taskKey);
    logger.info("请求信用卡列表");
    var accountInfoUrl = "https://mbs.boc.cn/BOCWapBank/CRCDAccountList.do?_MenuId=mbsmenu.creditcard.query.queryAccountInfomation";
    //TODO  这里可能需要其他headers  -------目前不需要
    var accountInfoHtml = executeGet(accountInfoUrl, null);
    storeDataToFile(context, accountInfoHtml, "wap_cardList.html");
    var doc = Jsoup.parse(accountInfoHtml);
    //这里取选择 label标签， 因为可能为多卡
    var elements = doc.select(".wapbody > form:nth-child(3) > p:nth-child(1) > label");
    var cardList = new LinkedList();

    // 检查当前账户是否具有卡
    var checkCardList = function (elements) {
        if(elements.isEmpty()){
            logger.info("中国taskKey={},获取卡号列表为空，停止抓取", taskKey);
            return false
        }
        return true
    }
    var getCheckCardErrorMsg = function (elements) {
        return "未获取到卡片信息，请登录官网绑定卡片";
    }
    assertTrueOrThrowException(elements, checkCardList, getCheckCardErrorMsg);


    if (elements.isEmpty()) {
        logger.info("中国taskKey={},获取卡号列表为空，停止抓取", taskKey);
        throw new BankException(BankConstants.BALO_20304_30, "获取到的卡列表为空，停止抓取");
    } else {
        for (var i = 0; i < elements.size(); i++) {
            var element = elements.get(i);
            var crcdAccountId = element.attr("for");
            cardList.add(crcdAccountId);
        }
    }
    var _tokenName = doc.select(".wapbody > form:nth-child(3) > p:nth-child(1) > input:nth-child(1)").attr("value");
    logger.info("中国 taskKey={}，wap版本，获取到信用卡有{}张", taskKey, cardList.size());
    if (cardList.size() !== 0) {
        for (var i = 0; i < cardList.size(); i++) {
            var creditCardAllData = new CreditCardAllData();
            logger.info("开始抓取第{}张， 该卡的id为{}", i + 1, cardList.get(i));
            var crcdAccountId = cardList.get(i);
            crawlCreditBasicInfoOnWap(creditCardAllData, crcdAccountId, _tokenName);
            crawlCreditUndoneBillOnWap(creditCardAllData, crcdAccountId);
            crawlCreditDoneBillOnWap(creditCardAllData, crcdAccountId);
            //在这里去处理分期等信息  不知道这个分期啥效果
            handleUndoneBillInfo(creditCardAllData);
            dataList.add(creditCardAllData);
        }
    } else {
        logger.info("中国taskKey={},获取卡号列表为空，停止抓取", taskKey);
        throw new BankException(BankConstants.BALO_20304_30, "获取到的卡列表为空，停止抓取");
    }
}

/**
 *  信用卡wap版本 -抓取账户的基本信息
 * @param creditCardAllData
 * @param crcdAccountId 账户id
 * @
 */
function crawlCreditBasicInfoOnWap(creditCardAllData, crcdAccountId, _tokenName) {
    logger.info("中国 taskKey={}，请求账户的额度等信息", context.get(Constants.LUA_TASK_KEY));
    var basicInfoUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQueryResult.do";
    var param = new LinkedHashMap();
    param.put("_tokenName", _tokenName);
    param.put("crcdAccountId", crcdAccountId);
    param.put("Submit", "确定");
    var basicInfo = executePostWithParam(basicInfoUrl, param, null);
    storeDataToFile(context, basicInfo, wapCreditCardNum + "_wap_basicInfo.html");
    var doc = Jsoup.parse(basicInfo);
    var select = doc.select(".wapbody");
    if (select.isEmpty()) {
        logger.info("中国 taskKey={}获取账户的额度等信息失败，停止解析", context.get(Constants.LUA_TASK_KEY));
        return;
    }
    var allInfos = select.html().replaceAll("\r", "").replaceAll("\n", "");
    var full_card_num = allInfos.substring(allInfos.indexOf("您选择的信用卡") + 8, allInfos.indexOf("<br style="));
    creditCardAllData.setFullCardNum(full_card_num);
    if (full_card_num.length() > 4) {
        var card_num = full_card_num.substring(full_card_num.length() - 4, full_card_num.length());
        creditCardAllData.setCardNum(card_num);
    }
    creditCardAllData.setBankName("中国银行");
    creditCardAllData.setCardId(UUID.randomUUID().toString());
    creditCardAllData.setCardType("信用卡");
    creditCardAllData.setBankName(name_on_card_wap);
    var basicInfos = allInfos.split("<br>");
    if (basicInfos !== null && basicInfos.length > 0) {
        for each(var info
    in
        basicInfos
    )
        {
            if (info.contains("总授信额度")) {
                var credit_limit = info.substring(info.indexOf("：") + 1, info.length());
                creditCardAllData.setCreditLimit(CreditResultUtil.StringToBigDecimal(credit_limit.trim()));
            }
            if (info.contains("总可用额")) {
                var balance = info.substring(info.indexOf("：") + 1, info.length());
                creditCardAllData.setBalance(CreditResultUtil.StringToBigDecimal(balance.trim()));
            }
            if (info.contains("取现额度")) {
                var cash_limit = info.substring(info.indexOf("：") + 1, info.length());
                creditCardAllData.setCashLimit(CreditResultUtil.StringToBigDecimal(cash_limit.trim()));
            }
            if (info.contains("取现可用额")) {
                var cash_balance = info.substring(info.indexOf("：") + 1, info.length());
                creditCardAllData.setCashBalance(CreditResultUtil.StringToBigDecimal(cash_balance.trim()));
            }
            if (info.contains("币种")) {
                var currecy = info.substring(info.indexOf("：") + 1, info.length());
                logger.info("中国 taskKey={},当前账户的币种信息为{}", context.get(Constants.LUA_TASK_KEY), currecy);
            }
        }
    }
}


/**
 *  信用卡wap版本 -抓取账户的未出账单
 * @param creditCardAllData
 * @param crcdAccountId 账户id
 * @throws Exception
 */
function crawlCreditUndoneBillOnWap(creditCardAllData, crcdAccountId) {
    var taskKey = context.get(Constants.LUA_TASK_KEY);
    logger.info("中国 taskKey={} 开始抓取未出账单信息", taskKey);
    //暂定的步骤为  1 请求未出账单，然后 会出现卡的列表 ，从中取出 tokenName  2.请求未出账单列表
    var queryUndoneBillUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillCardList.do?_MenuId=mbsmenu.creditcard.query.queryTransferDetail";
    var queryUndoneBillHtml = executeGet(queryUndoneBillUrl, null);
    storeDataToFile(context, queryUndoneBillHtml, wapCreditCardNum + "_wap_queryUndoneHtml.html");
    var doc = Jsoup.parse(queryUndoneBillHtml);
    var _tokenName = doc.select(".wapbody > form:nth-child(3) > p:nth-child(1) > input:nth-child(1)").attr("value");
    var param = new LinkedHashMap();
    param.put("FromAccountId", crcdAccountId);
    param.put("Submit", "确定");
    param.put("_tokenName", _tokenName);//该参数需要请求页面来确定  每一次下个请求，该参数都会发生变化
    var undoneBillListUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillList.do";
    var undoneBillPageOne = executePostWithParam(undoneBillListUrl, param, null);
    storeDataToFile(context, undoneBillPageOne, wapCreditCardNum + "_wap_undoneBillList_1.html");
    //TODO 填充表头
    var billAllData = new BillAllData();
    billAllData.setBankName("中国银行");
    billAllData.setBillId(UUID.randomUUID().toString());
    billAllData.setBillType("UNDONE");
    billAllData.setCashLimit(creditCardAllData.getCashLimit());
    billAllData.setCreditLimit(creditCardAllData.getCreditLimit());

    billAllData.setLastPayment(null);
    billAllData.setNewCharges(null);
    billAllData.setMinPayment(null);
    billAllData.setInterest(null);

    //这里暂定美元为nulls
    billAllData.setUsdNewCharges(null);
    billAllData.setUsdCashLimit(null);
    billAllData.setUsdCreditLimit(null);
    billAllData.setUsdInterest(null);
    billAllData.setUsdLastBalance(null);
    billAllData.setUsdLastPayment(null);
    billAllData.setUsdMinPayment(null);
    billAllData.setUsdNewBalance(null);
    billAllData.setUsdNewCharges(null);
    creditCardAllData.getBills().add(billAllData);
    for (var i = 1; ; i++) {//这里可能有死循环
        var document = Jsoup.parse(undoneBillPageOne);
        var startRow = document.select("#form1 > p:nth-child(2) > input:nth-child(1)").attr("value");
        //TODO 这里考虑下如果没有的情况下该怎么半  暂定为  如果所有的subid如果没有 那就是没有未出账单 即 循环遍历所有为input的输入框，如果没有那么就认定为当前页面无数据
        logger.info("中国 taskKey={}解析未出账单列表第{}页", taskKey, i);
        parseUndoneBillDetailOnWap(document, billAllData, startRow, i);
        //第一页到第二页：https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillListPage.do?START_ROW=10   get请求
        var nextPageFlag = document.select("#form1 > p:nth-child(2) > a:nth-child(2)");
        if (!nextPageFlag.isEmpty() && nextPageFlag.html().contains("下一页")) {
            logger.info("中国 taskKey={}解析未出账单列表第{}页,当前页面具有下一页，继续请求", taskKey, i);
            var nextPageUrl = "https://mbs.boc.cn/BOCWapBank/" + nextPageFlag.attr("href");
            var morePageList = executeGet(nextPageUrl, null);
            storeDataToFile(context, morePageList, wapCreditCardNum + "_wap_undoneBillList_" + (i + 1) + ".html");
            undoneBillPageOne = morePageList;
        } else {
            logger.info("中国 taskKey={}解析未出账单列表第{}页,当前页面没有有下一页，停止解析请求", taskKey, i);
            return;
        }
    }
}
/**
 * 解析未出账单的页面，也有可能会解析已出账单的
 * @param startRow
 * @param billAllData
 * @throws Exception
 */
function parseUndoneBillDetailOnWap(document, billAllData, startRow, pageNum) {
    //问题，第一页和第二页的tokenName是否是一样的？ 很有可能是不一样的 暂定为不一样  -------不一样
    var unDoneBillList__tokenName = document.select("#form1 > p:nth-child(1) > input:nth-child(1)").attr("value");
    var elements = document.select("#form1 > p:nth-child(1) > input");
    if (elements == null || elements.isEmpty()) {
        logger.info("中国taskKey={}当前页面无为input的元素，停止向下请求 、解析", context.get(Constants.LUA_TASK_KEY));
        return;
    }
    var undoneDetailParam = new HashMap();
    undoneDetailParam.put("startRow", startRow);
    undoneDetailParam.put("Submit", "确定");
    var index = 0;
    //这里仍然需要取出_tokenName  每一个列表取出来 去获得详细信息 参数信息：_tokenName=""&smId=应该是第几个""&startRow=开始的页数""&Submit="确定"
    for each(var element
in
    elements
)
    {
        var unDoneBillDetailUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillDetail.do";
        var name = element.attr("name");
        if (name.contains("smId")) {
            index++;
            var value = element.attr("value");
            undoneDetailParam.put("smId", value);
            //TODO 看怎么去判断是不是最后一页
            undoneDetailParam.put("_tokenName", unDoneBillList__tokenName);
            var undoneDetailHtml = executePostWithParam(unDoneBillDetailUrl, undoneDetailParam, null);
            storeDataToFile(context, undoneDetailHtml, wapCreditCardNum + "_wap_undoneDetail_" + pageNum + "_" + value + ".html");
            //这里同样需要 使用前一种方式去解析页面
            var undoneDetailDoc = Jsoup.parse(undoneDetailHtml);
            var allInfoELement = undoneDetailDoc.select(".wapbody");
            if (!allInfoELement.isEmpty()) {
                var allInfo = allInfoELement.html().replaceAll("\r", "").replaceAll("\n", "").trim();
                var basicInfos = allInfo.split("<br>");
                if (basicInfos !== null && basicInfos.length > 0) {
                    var expense = new Expense();
                    expense.setId(UUID.randomUUID().toString());
                    expense.setOrderIndex((billAllData.getShoppingSheets().size() + 1));
                    expense.setCurrencyType("CNY");
                    expense.setBalance(null);
                    billAllData.getShoppingSheets().add(expense);
                    var currecy = "";
                    for each(var info in basicInfos ){
                        if (info.contains("交易日期")) {
                            var trans_date = info.substring(info.indexOf("：") + 1, info.length());
                            trans_date = trans_date.replaceAll("/", "-").trim();
                            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date + " 00:00:00"));
                        }
                        if (info.contains("记账日期")) {
                            var post_date = info.substring(info.indexOf("：") + 1, info.length());
                            post_date = post_date.replaceAll("/", "-");
                            expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                        }
                        if (info.contains("记账币种")) {
                            currecy = info.substring(info.indexOf("：") + 1, info.length());
                            var currecyType = CreditResultUtil.convertCurr(currecy);
                            expense.setCurrencyType(currecyType);
                        }
                        if (info.trim().contains("卡　　号")) {
                            var card_num = info.substring(info.indexOf("：") + 1, info.length()).trim();
                            expense.setCardNum(card_num);
                        }
                        if (info.contains("交易类型")) {
                            var category = info.substring(info.indexOf("：") + 1, info.length());
                            expense.setCategory(category);
                        }
                        if (info.contains("交易描述")) {
                            var description = info.substring(info.indexOf("：") + 1, info.length());
                            expense.setDescription(description);
                        }
                        if (info.contains("存入金额")) {
                            var depositAmount = info.substring(info.indexOf("：") + 1, info.length());
                            if (!depositAmount.contains("--") && depositAmount.contains(currecy.trim())) {//证明当前 不为存入金额
                                var amountMoney = depositAmount.replaceAll(currecy.trim(), "");
                                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal("-" + amountMoney));
                                expense.setCategory(CategoryUtil.getCreditCategory("BOC", expense.getCategory(), amountMoney));
                            }
                        }
                        if (info.contains("支出金额")) {
                            var spendMoney = info.substring(info.indexOf("：") + 1, info.length());
                            if (spendMoney.contains(currecy.trim())) {//证明当前 不为存入金额
                                var amountMoney = spendMoney.replaceAll(currecy.trim(), "");
                                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amountMoney));
                                expense.setCategory(CategoryUtil.getCreditCategory("BOC", expense.getCategory(), amountMoney));
                            }
                        }

                    }
                    var newBalance = billAllData.getNewBalance();
                    billAllData.setNewBalance(newBalance.add(expense.getAmountMoney()));//所有的值
                }
            } else {
                logger.info("中国 taskKey={}当前账单的详细信息为空，停止解析", context.get(Constants.LUA_TASK_KEY));
                return;
            }
        }
        //这里返回去获取  _tokenName
        var backUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillDetailBack.do";
        var backParam = new HashMap();
        backParam.put("StartRow", startRow);
        backParam.put("Submit2", "返回");
        var backHtml = executePostWithParam(backUrl, backParam, null);
        unDoneBillList__tokenName = Jsoup.parse(backHtml).select("#form1 > p:nth-child(1) > input:nth-child(1)").attr("value");
    }
    if (index == 0) {
        logger.info("中国 taskKey={} 当前页面无账单信息数据，没有解析");
        return;
    }
}


/**
 *  信用卡wap版本 -抓取账户的已出账单
 * @param creditCardAllData
 * @param crcdAccountId 账户id
 * @throws Exception
 */
function crawlCreditDoneBillOnWap(creditCardAllData, crcdAccountId) {
    var taskKey = context.get(Constants.LUA_TASK_KEY);
    logger.info("中国 taskKey={} 开始抓取已出账单信息", taskKey);
    var queryDoneBillUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisCardList.do?_MenuId=mbsmenu.creditcard.query.queryStatement";
    var queryDoneHtml = executeGet(queryDoneBillUrl, null);
    storeDataToFile(context, queryDoneHtml, wapCreditCardNum + "_wap_queryDoneHtml.html");
    var document = Jsoup.parse(queryDoneHtml);
    var _tokenName = document.select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    var elements = document.select(".wapbody > form:nth-child(2) > p:nth-child(1) > select:nth-child(6)>option");//月份的列表
    if (elements.isEmpty()) {
        logger.info("中国 taskKey={}唔可以查询的已出账单的月份，停止抓取已出账单", taskKey);
        return;
    } else {
        logger.info("", elements.size());
    }
    var param = new HashMap();
    param.put("Submit", "确定");
    param.put("SelCrcdId", crcdAccountId);
    var calendar = Calendar.getInstance();
    var format = new SimpleDateFormat("yyyy/MM");
    for (var i = 0; i < 6; i++) {
        Thread.sleep(2000)
//		for (var element : elements) {
        param.put("_tokenName", _tokenName);
        //每个月的参数信息 ：_tokenName=&&SelCrcdId=账户的id&&CrcdStatementMonth=月份&&Submit=确定
//			var month=element.attr("value");
        var month = format.format(calendar.getTime());
        calendar.add(Calendar.MONTH, -1);
        //测试 ：month 为 2017/7
        param.put("CrcdStatementMonth", month);
//			param.put("CrcdStatementMonth", month);
        var billAllData = new BillAllData();
        creditCardAllData.getBills().add(billAllData);
        billAllData.setBankName("中国银行");
        billAllData.setBillId(UUID.randomUUID().toString());
        billAllData.setBillType("DONE");
        billAllData.setBillMonth(month.replaceAll("/", "-"));
        billAllData.setCashLimit(creditCardAllData.getCashLimit());
        billAllData.setCreditLimit(creditCardAllData.getCreditLimit());
        billAllData.setNewCharges(null);
        billAllData.setInterest(null);
        billAllData.setNewCharges(null);

        billAllData.setUsdNewCharges(null);
        billAllData.setUsdCashLimit(null);
        billAllData.setUsdCreditLimit(null);
        billAllData.setUsdInterest(null);
        billAllData.setUsdLastBalance(null);
        billAllData.setUsdLastPayment(null);
        billAllData.setUsdMinPayment(null);
        billAllData.setUsdNewBalance(null);
        billAllData.setUsdNewCharges(null);
        crawlMonthDoneBillOnWap(billAllData, month, param);
        handleInstalmentOnWap(billAllData);
        var loginBackUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisCardList.do";
        var backParam = new HashMap();
        backParam.put("Submit2", "取消");
        var queryHtml = executePostWithParam(loginBackUrl, backParam, null);
        var queryDoc = Jsoup.parse(queryHtml);
        _tokenName = queryDoc.select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    }
}

/**
 * 抓取月份的已出账单
 * @param month
 * @throws Exception
 * @month
 */
function crawlMonthDoneBillOnWap(billAllData, month, param) {
    var taskKey = context.get(Constants.LUA_TASK_KEY);
    logger.info("中国 taskKey={}开始抓取{}月分的已出账单", taskKey, month);
    var doneMonthUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBillSummary.do";
    var monthDoneBillHtml = executePostWithParam(doneMonthUrl, param, null);
    storeDataToFile(context, monthDoneBillHtml, wapCreditCardNum + "_wap_" + month + "donebillHtml_1.html");//该月第一页
    if (monthDoneBillHtml.contains("无符合查询条件的记录，请重新查询")) {
        logger.info("当前页面没有需要账单信息，停止解析");
        billAllData.setLastBalance(null);
        billAllData.setLastPayment(null);
        billAllData.setNewBalance(null);
        billAllData.setMinPayment(null);
        return;
    }
    //这里去获取 账单详情页面
    var monthAccountInfoUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBillDetail.do";
    //参数信息：_tokenName:iai91644   CrcdViewTotalButton:当期账单总计     StartRow:0
    var document = Jsoup.parse(monthDoneBillHtml);
    var _tokenName = document.select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    var monthAccountInfoParam = new HashMap();
    monthAccountInfoParam.put("_tokenName", _tokenName);
    monthAccountInfoParam.put("CrcdViewTotalButton", "当期账单总计");
    monthAccountInfoParam.put("StartRow", "0");
    logger.info("中国 taskKey={}开始抓取{}月份的已出账单账单信息页面", taskKey, month);
    var monthAccountInfoHtml = executePostWithParam(monthAccountInfoUrl, monthAccountInfoParam, null);
    storeDataToFile(context, monthAccountInfoHtml, wapCreditCardNum + "_wap_+" + month + "_monthAccountInfo.html");
    //存储每个月的总的账户信息
    var monthAccounyInfoDoc = Jsoup.parse(monthAccountInfoHtml);
    var monthAccountInfoElement = monthAccounyInfoDoc.select(".wapbody");
    if (monthAccountInfoElement.isEmpty()) {
        logger.info("中国 taskKey={}开始解析{}月份的已出账单账单信息页面 为空，停止解析", taskKey, month);
    } else {
        var monthAccountInfos = monthAccountInfoElement.html().replaceAll("\r", "").replaceAll("\n", "").trim();
        var basicInfos = monthAccountInfos.split("<br>");
        if (basicInfos !== null && basicInfos.length > 0) {
            for each(var info
        in
            basicInfos
        )
            {
                if (info.contains("上期账面余额")) {
                    var last_balance = info.substring(info.indexOf("：") + 1, info.length());
                    if (last_balance.contains("欠款")) {
                        last_balance = last_balance.replaceAll("欠款", "").trim();
                        billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal(last_balance));
                    } else {
                        last_balance = last_balance.replaceAll("[\u4e00-\u9fa5]", "").trim();
                        billAllData.setLastBalance(CreditResultUtil.StringToBigDecimal("-" + last_balance));
                    }
                }
                if (info.contains("存入总计")) {
                    var last_payment = info.substring(info.indexOf("：") + 1, info.length());
                    last_payment = last_payment.replaceAll("[\u4e00-\u9fa5]", "").trim();
                    billAllData.setLastPayment(CreditResultUtil.StringToBigDecimal("-" + last_payment));
                }
                if (info.contains("到期还款日")) {//格式为2017/11/12
                    var payment_due_date = info.substring(info.indexOf("：") + 1, info.length());
                    payment_due_date = formatDate(payment_due_date.replaceAll("/", ""));
                    if(StringUtils.isNotBlank(payment_due_date)){
                        billAllData.setPaymentDueDate(yyyy_MM_dd_PARSER.parse(payment_due_date));
                    }
                }
                if (info.contains("支出总付")) {
                    var new_charges = info.substring(info.indexOf("：") + 1, info.length()).trim();
                    billAllData.setNewCharges(CreditResultUtil.StringToBigDecimal(new_charges));
                }
                if (info.contains("当期应还款金额")) {
                    var new_balance = info.substring(info.indexOf("：") + 1, info.length()).trim();
                    if (new_balance.contains("欠款")) {
                        new_balance = new_balance.replaceAll("欠款", "").trim();
                        billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal(new_balance));
                    } else {
                        new_balance = new_balance.replaceAll("[\u4e00-\u9fa5]", "");
                        billAllData.setNewBalance(CreditResultUtil.StringToBigDecimal("-" + new_balance));
                    }
                }
                if (info.contains("当期最低还款额")) {
                    var min_payment = info.substring(info.indexOf("：") + 1, info.length()).trim();
                    billAllData.setMinPayment(CreditResultUtil.StringToBigDecimal(min_payment));
                }//账单日期
                if (info.contains("账单日期")) {
                    var bill_date = info.substring(info.indexOf("：") + 1, info.length());
                    bill_date = bill_date.replaceAll("/", "-");
                    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(bill_date));
                }
            }
        }
    }
    var backUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBackToSummary.do";
    //参数信息为：Submit2=返回 StartRow=0 从这里取出_tokenNmae
    var backParam = new HashMap();
    backParam.put("Submit2", "返回");
    backParam.put("StartRow", "0");
    var backHtml = executePostWithParam(backUrl, backParam, null);
    var backDoc = Jsoup.parse(backHtml);
    _tokenName = backDoc.select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    for (var i = 1; ; i++) {//这里可能有死循环
        document = Jsoup.parse(monthDoneBillHtml);
        var startRow = document.select(".wapbody > form:nth-child(2) > p:nth-child(2) > input:nth-child(1)").attr("value");
        logger.info("中国 taskKey={}解析{}月已出账单列表第{}页", taskKey, month, i);
        parseDoneBillOnWap(document, billAllData, startRow, i, _tokenName);
        //第一页到第二页：https://mbs.boc.cn/BOCWapBank/CRCDQueryFutBillListPage.do?START_ROW=10   get请求
        var nextPageFlag = document.select(".wapbody > form:nth-child(2) > p:nth-child(2) > a:nth-child(2)");
        if (!nextPageFlag.isEmpty() && nextPageFlag.html().contains("下一页")) {
            logger.info("中国 taskKey={}解析未出账单列表第{}页,当前页面具有下一页，继续请求", taskKey, i);
            var nextPageUrl = "https://mbs.boc.cn/BOCWapBank/" + nextPageFlag.attr("href");
            var morePageList = executeGet(nextPageUrl, null);
            storeDataToFile(context, morePageList, wapCreditCardNum + "_wap_" + month + "_doneBillList_" + (i + 1) + ".html");
            monthDoneBillHtml = morePageList;
        } else {
            logger.info("中国 taskKey={}解析{}月已出账单列表第{}页,当前页面没有有下一页，停止解析请求", taskKey, month, i);
            return;
        }
    }
}

/**
 * 从账单中获取描述中含有分期的字段
 *    -->含有分期时
 *  -->含有分期手续费的时候
 *    从大到小排列起来
 * @param billAllData
 */
function handleInstalmentOnWap(billAllData) {
    var shopping_sheets = billAllData.getShoppingSheets();
    var installmentHandFee = new ArrayList();//账单中包含手续费用的集合
    var installments = new ArrayList();
    billAllData.setInstallments(installments);
    if (shopping_sheets.size() > 0) {
        logger.info("中国  taskKey={}分别寻找账单明细中含有分期或者分期手续费", context.get(Constants.LUA_TASK_KEY));
        for each(var expense
    in
        shopping_sheets
    )
        {
            var description = expense.getDescription();
            if(StringUtils.isBlank(description)){
                continue;
            }
            var category = expense.getCategory();
            if (!description.contains("手续费") && (description.contains("分期") || category.contains("INSTALLMENT"))) {//如果含有分期
                if (description.contains("分期成功")) {
                    continue;
                }
                var installment = new Installment();
                installment.setBillId(UUID.randomUUID().toString());
                installment.setAmountMoney(expense.getAmountMoney());
                installment.setCurrencyType(expense.getCurrencyType());
                installment.setInstallmentDesc(description);

                installment.setCurrentMonth(null);
                installment.setTransferFee(null);
                installment.setTotalMonth(null);
                installment.setShoppingsheetId(UUID.randomUUID().toString());

                //installment.setTransDate(expense.getTransDate());
                installment.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(TimeUtil.getTimeStr(TimeUtil.getTime(expense.getTransDate(), "yyyyMMdd"), "yyyy-MM-dd HH:mm:ss")));
                installment.setPostDate(expense.getPostDate());
                installment.setInstallmentType(judgeInstallmentType(description));
                installments.add(installment);
            }
            if (description.contains("分期付款手续费")) {//手续费
                var installment = new Installment();
                installment.setHandingFee(expense.getAmountMoney());
                installment.setHandingfeeDesc(expense.getDescription());
                installmentHandFee.add(installment);
            }
        }
        bubbleSort(installments, "");
        bubbleSort(installmentHandFee, "handfee");
        //这里开始对应
        logger.info("中国  taskKey={}分别对应分期和分期手续费,", context.get(Constants.LUA_TASK_KEY));
        if (installments.size() == installmentHandFee.size()) {
            for (var i = 0; i < installments.size(); i++) {
                var installment = installments.get(i);
                var handFee = installmentHandFee.get(i);
                installment.setHandingFee(handFee.getHandingFee());//
                installment.setHandingfeeDesc(handFee.getHandingfeeDesc());
            }
        } else {//手续费比分期的数据多  或者分期比手续费多
            logger.info("中国 taskkey={}分期手续费与分期对应出错,即分期和本金并不对应，分期的数量为{}，手续费的数量为{}", context.get(LUA_TASK_KEY), installments.size(), installmentHandFee.size());
            //按照分期的数量，从大大小一次 排序，如果没有设置为null
            for (var i = 0; i < installments.size(); i++) {//当现在的本金和 手续费都是按照费用从大到小的顺序排序
                var installment = installments.get(i);
                if ((i + 1) <= installmentHandFee.size()) {
                    var handFee = installmentHandFee.get(i);
                    installment.setHandingFee(handFee.getHandingFee());
                    installment.setHandingfeeDesc(handFee.getHandingfeeDesc());
                } else {
                    installment.setHandingFee(null);//如果当前分期对应的手续没有，那么手续费设置为null
                    installment.setHandingfeeDesc("");
                }

            }
        }

    }
}


/**
 * 解析已出账单页面的列表
 * @param doneBillListDoc
 * @param billAllData
 * @param startRow
 * @param pageNum
 * @throws Exception
 */
function parseDoneBillOnWap(doneBillListDoc, billAllData, startRow, pageNum, _tokenName) {
    //第一次时取外面传进来的，第二次取页面上的数据
    if (pageNum > 1) {
        _tokenName = doneBillListDoc.select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    }
    var doneDetailParam = new HashMap();
    doneDetailParam.put("startRow", startRow);
    doneDetailParam.put("CrcdViewDetailButton", "确定");
    var elements = doneBillListDoc.select(".wapbody >form:nth-child(2)>p>input");
    if (elements == null || elements.isEmpty()) {
        logger.info("中国taskKey={}当前页面无为input的元素，停止向下请求 、解析", context.get(Constants.LUA_TASK_KEY));
        return;
    }
    var index = 0;
    //_tokenName:ioj0yzi3   CrcdSmId:06  StartRow:0   CrcdViewDetailButton:确定
    for each(var element
in
    elements
)
    {
        var doneBillDetailUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBillDetail.do";
        var name = element.attr("name");
        if (name.contains("CrcdSmId")) {
            index++;
            var value = element.attr("value");
            doneDetailParam.put("_tokenName", _tokenName);
            doneDetailParam.put("CrcdSmId", value);
            var undoneDetailHtml = executePostWithParam(doneBillDetailUrl, doneDetailParam, null);
            storeDataToFile(context, undoneDetailHtml, wapCreditCardNum + "_wap_" + billAllData.getBillMonth() + "_doneDetail_" + pageNum + "_" + value + ".html");
            //这里同样需要 使用前一种方式去解析页面
            var undoneDetailDoc = Jsoup.parse(undoneDetailHtml);
            var allInfoELement = undoneDetailDoc.select(".wapbody");
            if (!allInfoELement.isEmpty()) {
                var allInfo = allInfoELement.html().replaceAll("\r", "").replaceAll("\n", "").trim();
                var basicInfos = allInfo.split("<br>");
                if (basicInfos !== null && basicInfos.length > 0) {
                    var expense = new Expense();
                    expense.setId(UUID.randomUUID().toString());
                    expense.setOrderIndex((billAllData.getShoppingSheets().size() + 1));
                    expense.setBalance(null);
                    billAllData.getShoppingSheets().add(expense);
                    var currecy = "";
                    for each(var info
                in
                    basicInfos
                )
                    {
                        if (info.contains("交易日期")) {
                            var trans_date = info.substring(info.indexOf("：") + 1, info.length());
                            trans_date = trans_date.replaceAll("/", "-").trim();
                            expense.setTransDate(yyyy_MM_dd_HH_mm_ss_PARSER.parse(trans_date +" 00:00:00"));
                        }
                        if (info.contains("记账日期")) {
                            var post_date = info.substring(info.indexOf("：") + 1, info.length());
                            post_date = post_date.replaceAll("/", "-");
                            expense.setPostDate(yyyy_MM_dd_PARSER.parse(post_date));
                        }
                        if (info.contains("记账币种")) {
                            currecy = info.substring(info.indexOf("：") + 1, info.length());
                            var currecyType = CreditResultUtil.convertCurr(currecy);
                            expense.setCurrencyType(currecyType);
                        }
                        if (info.replaceAll("\\s", "").contains("卡号")) {
                            var card_num = info.substring(info.indexOf("：") + 1, info.length()).trim();
                            expense.setCardNum(card_num);
                        }
                        if (info.contains("交易类型")) {
                            var category = info.substring(info.indexOf("：") + 1, info.length());
                            expense.setCategory(category);
                        }
                        if (info.contains("交易描述")) {
                            var description = info.substring(info.indexOf("：") + 1, info.length());
                            expense.setDescription(description);
                        }
                        if (info.contains("存入金额")) {
                            var depositAmount = info.substring(info.indexOf("：") + 1, info.length());
                            if (!depositAmount.contains("--") && depositAmount.contains(currecy.trim())) {//证明当前 不为存入金额
                                var amountMoney = depositAmount.replaceAll(currecy.trim(), "");
                                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal("-" + amountMoney));
                                expense.setCategory(CategoryUtil.getCreditCategory("BOC", info, amountMoney));
                            }
                        }

                        if (info.contains("支出金额")) {
                            var spendMoney = info.substring(info.indexOf("：") + 1, info.length());
                            if (!spendMoney.contains("--") && spendMoney.contains(currecy.trim())) {//证明当前 不为存入金额
                                var amountMoney = spendMoney.replaceAll(currecy.trim(), "");
                                expense.setAmountMoney(CreditResultUtil.StringToBigDecimal(amountMoney));
                                expense.setCategory(CategoryUtil.getCreditCategory("BOC", info, amountMoney));
                            }
                        }
                    }
                }
            } else {
                logger.info("中国 taskKey={}当前账单的详细信息为空，停止解析", context.get(Constants.LUA_TASK_KEY));
                return;
            }
        }
        var backUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBackToSummary.do";
        var backParam = new HashMap();
        backParam.put("StartRow", startRow);
        backParam.put("Submit2", "返回");
        var backHtml = executePostWithParam(backUrl, backParam, null);
        _tokenName = Jsoup.parse(backHtml).select(".wapbody > form:nth-child(2) > p:nth-child(1) > input:nth-child(1)").attr("value");
    }
    if (index == 0) {
        logger.info("中国 taskKey={} 当前页面无账单信息数据，没有解析");
        return;
    }
    //每一个页的详细 参数信息：_tokenName=&&CrcdSmId=&&StartRow=&&CrcdViewDetailButton="确定"
    var queryDetailUrl = "https://mbs.boc.cn/BOCWapBank/CRCDQryHisBillDetail.do";
}


/**
 * 根据分期的金额来排序 从小到大来排序
 * @param list
 */
function bubbleSort(list, flag) {
    for (var i = 0; i < list.size() - 1; i++) {
        for (var j = 0; j < list.size() - 1; j++) {
            var currentBigdecimal = null;
            var nextBigdecimal = null;
            if (flag.equals("")) {//为空的时候取本金
                currentBigdecimal = list.get(j).getAmountMoney();
                nextBigdecimal = list.get(j + 1).getAmountMoney();
            } else {//不为空的时候取手续费
                currentBigdecimal = list.get(j).getHandingFee();
                nextBigdecimal = list.get(j + 1).getHandingFee();//
            }
            if (nextBigdecimal.compareTo(currentBigdecimal) == 1) {//当前分期的金额大于下一个
                //var temp=list.get(j);
                var tempInstallment = list.get(j);
                list.set(j, list.get(j + 1));
                list.set(j + 1, tempInstallment);
            }
        }
    }
}


/**
 *    对未出账单的一些没有的信息进行填充
 *        未出账单的billdate  billmonth  last_balance new_balance
 *            -->billdate billmonth 根据取值的账单的顺序来计算
 *            -->last_balance new_balance取下一期账单的值
 * @throws ParseException
 */
function handleUndoneBillInfo(creditCardAllData) {
    //获取账单日
    var billDate = "";
    var billDaye = 0;//账单的天数
    var last_balance = null;
    var bills = creditCardAllData.getBills();
    try {
        for (var i = 0; i < bills.size(); i++) {
            var billAllData = bills.get(i);
            var bill_date=billAllData.getBillDate();
            if(bill_date==null){
                continue;
            }
            // bill_date = yyyy_MM_dd_PARSER.format(bill_date);
            if (bill_date.length() > 0) {//此处有值
                var format = new SimpleDateFormat("yyyy-MM-dd");
                var parse = format.parse(bill_date);
                var calendar = Calendar.getInstance();
                calendar.setTime(parse);
                billDaye = calendar.get(Calendar.DAY_OF_MONTH);
                break;
            }
        }
        var calendar = Calendar.getInstance();
        var cuurentDay = calendar.get(Calendar.DAY_OF_MONTH);
        if (cuurentDay < billDaye) {//今天小于billday的时候，那么11月就是未出账单
            if (bills.size() > 0) {
                bills.remove(1);
            }
        }
        for (var i = 0; i < bills.size(); i++) {
            var billAllData = bills.get(i);
            var bill_date = yyyy_MM_dd_PARSER.format(billAllData.getBillDate());
            if (i == 1) {
                last_balance = bills.get(i).getNewBalance();
            }
            if (bill_date.length() > 0) {//此处有值
                var format = new SimpleDateFormat("yyyy-MM-dd");
                var parse = format.parse(bill_date);
                calendar.setTime(parse);
                calendar.add(Calendar.MONTH, i);
                billDate = format.format(calendar.getTime());
                break;
            }
        }
        //取未出后面的后一个账单 在循环里取出一个账单日  2017-10-23
        if (billDate.length() > 3) {
            for each(var billAllData
        in
            bills
        )
            {
                var bill_type = billAllData.getBillType();
                var bill_date = yyyy_MM_dd_PARSER.format(billAllData.getBillDate());
                if (bill_type.equals("UNDONE")) {
                    if (last_balance !== null) {
                        billAllData.setLastBalance(last_balance);
                        billAllData.setNewBalance(billAllData.getNewBalance().add(last_balance));
                    } else {
                        billAllData.setLastBalance(null);
                    }
                    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billDate));
                    billAllData.setBillMonth(billDate.substring(0, billDate.length() - 3));
                }
                if (bill_date.length() == 0 && bill_type.equals("DONE")) {
                    billAllData.setBillDate(yyyy_MM_dd_PARSER.parse(billAllData.getBillMonth() + "-" + billDaye));
                }
            }
        }
    } catch (e) {
        logger.error("中国 taskKey={} 解析账单日出错，错误原因为{}", context.get(Constants.LUA_TASK_KEY), e);
        statCaughtException(context, e);
    }
}


/**
 * ------------业务方法结束-------------
 *
 *
 */

/**
 * 根据描述来判断分期的类型
 * @param type
 * @return
 */
function judgeInstallmentType(type) {
    var needType = "CONSUME";
    if (type !== null && type.length() > 0) {
        if (type.contains("账单") || type.contains("bill")) {
            needType = "BILL";
        } else if (type.contains("消费")) {
            needType = "CONSUME";
        } else if (type.contains("现金")) {
            needType = "CASH";
        }
    }
    return needType;
}

function executePostWithParam(url, param, headers) {
    logger.info("HttpClient执行Post请求，地址为{}", url);
    var header = new HashMap();
    header.put("User-Agent", USER_AGENT);
    header.put("Connection","keep-alive");
    header.put("Host","mbs.boc.cn");
    header.put("Cache-Control", "no-cache");
    var responseHtml = RequestUtil.post(url, param, header);
    return responseHtml;
}

/**
 *  get请求防止后期增加headers，
 * @param url
 * @param headers 如果需要传入本请求独特的header传入即可，如不需要，设置为null
 * @return
 * @throws Exception
 */

function executeGet(url, headers) {
    logger.info("HttpClient执行Get请求,地址为{}", url);
    var header = new HashMap();
    header.put("User-Agent", USER_AGENT);
    header.put("Connection","keep-alive");
    header.put("Host","mbs.boc.cn");
    header.put("Cache-Control", "no-cache");
    var responseHtml = RequestUtil.get(url, null, headers);
    return responseHtml;
}


/**
 * 借记卡 规范日期返回日期
 *
 * @param dateStr
 *            formatDate('20170507')
 * @return 2017-05-07
 */
function formatDate(dateStr) {
    if (dateStr == null || dateStr.trim().replaceAll('\s',"").length==0) {
        return "";
    }
    dateStr = RegexUtils.GetText(dateStr, "(\\d+)");
    var d = null;
    try {
        d = DateUtils.parseDate(dateStr, "yyyyMMdd");
    } catch (e) {
        logger.error("解析日期格式出错" + dateStr, e);
        statCaughtException(context, e);
    }
    dateStr = DateFormatUtils.format(d, "yyyy-MM-dd");
    return dateStr;
}